<?php
// Copyright 2004-present Facebook. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

class WebDriverDispatcher {

  /**
   * @var array
   */
  protected $listeners = array();

  /**
   * @var EventFiringWebDriver
   */
  protected $driver = null;

  /**
   * this is needed so that EventFiringWebElement can pass the driver to the
   * exception handling
   *
   * @param EventFiringWebDriver $driver
   * @return $this
   */
  public function setDefaultDriver(EventFiringWebDriver $driver) {
    $this->driver = $driver;
    return $this;
  }

  /**
   * @return null|EventFiringWebDriver
   */
  public function getDefaultDriver() {
    return $this->driver;
  }

  /**
   * @param WebDriverEventListener $listener
   * @return $this
   */
  public function register(WebDriverEventListener $listener) {
    $this->listeners[] = $listener;
    return $this;
  }

  /**
   * @param WebDriverEventListener $listener
   * @return $this
   */
  public function unregister(WebDriverEventListener $listener) {
    $key = array_search($listener, $this->listeners, true);
    if ($key !== false) {
      unset($this->listeners[$key]);
    }
    return $this;
  }

  /**
   * @param mixed $method
   * @param mixed $arguments
   * @return $this
   */
  public function dispatch($method, $arguments) {
    foreach ($this->listeners as $listener) {
      call_user_func_array(array($listener, $method), $arguments);
    }
    return $this;
  }

}
